package com.maserb.monitor.service.schoolForum.impl;

import com.maserb.monitor.entity.schoolForum.CommentEntity;
import com.maserb.monitor.entity.schoolForum.CommentReplyEntity;
import com.maserb.monitor.repository.schoolForum.CommentReplyRepository;
import com.maserb.monitor.service.base.impl.JpaSpecificationServiceImpl;
import com.maserb.monitor.service.schoolForum.CommentReplyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.StringUtils;

import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.List;

@Service
public class CommentReplyServiceImpl extends JpaSpecificationServiceImpl<CommentReplyRepository,
        CommentReplyRepository, CommentReplyEntity, String>
        implements CommentReplyService {

    @Autowired
    private CommentReplyRepository commentReplyRepository;

    private Specification<CommentReplyEntity> getSpecification(String commentId) {
        return new Specification<CommentReplyEntity>()  {
            @Override
            public Predicate toPredicate(Root<CommentReplyEntity> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                Join<CommentReplyEntity, CommentEntity> commentJoin = root.join("comment", JoinType.LEFT);
                Path<String> pathCommentId = commentJoin.get("id");
                ArrayList<Predicate> list = new ArrayList<Predicate>();
                list.add(criteriaBuilder.and(criteriaBuilder.equal(pathCommentId, commentId)));
                /*if (!StringUtils.isEmptyOrWhitespace(commentId)) {

                }*/
                return criteriaBuilder.and(list.toArray(new Predicate[list.size()]));
            }
        };
    }

    @Override
    public Page<CommentReplyEntity> findAll(Pageable pageable, String commentId) {
        return this.findAll(getSpecification(commentId), pageable);
    }

    @Override
    public List<CommentReplyEntity> findTopReplyList(CommentEntity comment) {
        return commentReplyRepository.findTop3ByCommentOrderByCreateTimeDesc(comment);
    }
}